// index.js
const defaultAvatarUrl = 'https://mmbiz.qpic.cn/mmbiz/icTdbqWNOwNRna42FI242Lcia07jQodd2FJGIYQfG0LAJGFxM4FbnQP6yfMxBgJ0F3YRqJCJ1aPAK2dQagdusBZg/0'

import {
  login,login_code
} from "../../services/login/login";

import {
  getUserInfo
} from "../../services/usercenter/user";


import Message from 'tdesign-miniprogram/message/index';
var app=getApp()


Page({
  data: {
    motto: '如果用户名不存在，则自行注册',
    userInfo: {
      avatarUrl: defaultAvatarUrl,
      nickName: '',
      textPassword:""
    },
    textPassword: "",
    hasUserInfo: false,
    canIUseGetUserProfile: wx.canIUse('getUserProfile'),
    canIUseNicknameComp: wx.canIUse('input.type.nickname'),
  },
  // 用户名登录

  // 微信登录
  wechatLogin() {
    var that =this
    // 点击微信登录按钮
    console.log("点击微信登录按钮");
    wx.login({
      success(res) {
        if (res.code) {
          //发起网络请求
          console.log(res);
          that.submitlogin_code(res.code)
        }
      }
    })
  },
  codeLogin(){
    // 点击了密码登录
    console.log("点击了密码登录");
    if(this.data.userInfo.nickName==="" || this.data.userInfo.nickName===undefined){
      Message.info({
        context: this,
        offset: ['20rpx', '32rpx'],
        duration: 2000,
        content: "用户名为空"
      });
      return;
    }

    if(this.data.userInfo.textPassword==="" || this.data.userInfo.textPassword===undefined){
      Message.info({
        context: this,
        offset: ['20rpx', '32rpx'],
        duration: 2000,
        content: "密码为空"
      });
      return;
    }

    // 点击登录
    this.submitLogin({
      username:this.data.userInfo.nickName,
      password:this.data.userInfo.textPassword
    })

  },
  submitlogin_code(code){
    var that=this;
    login_code({
      code: code
    }).then(res => {
      if (res.data.code === 200) {
        const token = "Bearer " + res.data.data.token;
        wx.setStorageSync('token', token)
        console.log("用户登录token");
        console.log(token);
        app.globalData.token = token;
        app.globalData.uid = res.data.data.uid;
        console.log("全局变量token");
        console.log(app.globalData.token);
        // 如果是新用户，通知时间长一点
        if (res.data.data.isNewUser === true) {
          Message.info({
            context: this,
            offset: ['20rpx', '32rpx'],
            duration: 5000,
            content: '新用户：' + res.data.data.username + " 新用户密码默认：123",
          });
        } else {
          Message.info({
            context: this,
            offset: ['20rpx', '32rpx'],
            duration: 2000,
            content: "登录成功"
          });
        }
        that.jump();
      } else {
        Message.info({
          context: this,
          offset: ['20rpx', '32rpx'],
          duration: 2000,
          content: res.data.data
        });
      }
    }).catch(error=>{
      Message.error({
        context: this,
        offset: ['20rpx', '32rpx'],
        duration: 2000,
        content: "网络发生错误"
      });
    })
  },

   async submitLogin(data) {
     var that=this;
    login(data).then(async res => {
      console.log(res);
      if (res.data.code === 200) {
        const token = "Bearer " + res.data.data;
        wx.setStorageSync('token', token)
        console.log("用户登录token");
        console.log(token);
        app.globalData.token = token;
        const userInfo= await getUserInfo();
        console.log(userInfo);
        app.globalData.uid = userInfo.data.data.id;
        console.log("全局变量token");
        console.log(app.globalData.token);
        console.log("全局变量uid");
        console.log(app.globalData.uid);
        that.jump();
      } else {
        Message.info({
          context: this,
          offset: ['20rpx', '32rpx'],
          duration: 2000,
          content: res.data.message
        });
      }
    }).catch(error=>{
      Message.error({
        context: this,
        offset: ['20rpx', '32rpx'],
        duration: 2000,
        content: "网络发生错误"
      });
    })
  },
  jump(){
    console.log("点击跳转")
    wx.switchTab({
      url: '/pages/index/index'
    })
  },

  bindViewTap() {
    wx.navigateTo({
      url: '../logs/logs'
    })
  },
  onChooseAvatar(e) {
    const {
      avatarUrl
    } = e.detail
    const {
      nickName
    } = this.data.userInfo
    this.setData({
      "userInfo.avatarUrl": avatarUrl,
      // hasUserInfo: nickName && avatarUrl && avatarUrl !== defaultAvatarUrl,
    })
  },
  onInputChange(e) {
    const nickName = e.detail.value
    const {avatarUrl} = this.data.userInfo
    this.setData({
      "userInfo.nickName": nickName,
    })
  },
  // 点击了密码按钮
  onPasswordChange(e) {
    const password = e.detail.value
    this.setData({
      "userInfo.textPassword": password
    })
  },
  // getUserProfile(e) {
  //   // 推荐使用wx.getUserProfile获取用户信息，开发者每次通过该接口获取用户个人信息均需用户确认，开发者妥善保管用户快速填写的头像昵称，避免重复弹窗
  //   wx.getUserProfile({
  //     desc: '展示用户信息', // 声明获取用户个人信息后的用途，后续会展示在弹窗中，请谨慎填写
  //     success: (res) => {
  //       console.log(res)
  //       this.setData({
  //         userInfo: res.userInfo,
  //         hasUserInfo: true
  //       })
  //     }
  //   })
  // },
})